import { pageCustomersListTruckOrderFees, exportData, deleteTruckOrderExtendFee } from '@/services/order/order_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
    ProTable,
    TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useModel } from '@umijs/max';
import { Button, Drawer, Input, message, Modal, Popconfirm, Card, Select, DatePicker, Form, Space, Collapse, Tabs, Typography } from 'antd';
import type { GetProp, TableProps } from "antd";
import React, { useRef, useState, useEffect } from 'react';
import type { RangePickerProps } from 'antd/es/date-picker';
import { TruckOrderFeeDetailVO } from '../types'
import dayjs from 'dayjs';
import type { SorterResult } from "antd/es/table/interface";
import EditForm from './components/EditForm'
import qs from 'qs';
import { formatToLocalTime } from '@/utils/time';
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

type TablePaginationConfig = Exclude<
    GetProp<TableProps, "pagination">,
    boolean
>;

interface TableParams {
    pagination?: TablePaginationConfig;
    sortField?: SorterResult<any>["field"];
    sortOrder?: SorterResult<any>["order"];
    filters?: Parameters<GetProp<TableProps, "onChange">>[1];
}

// 后端枚举映射


const TableList: React.FC = () => {
    /**
    * @en-US International configuration
    * @zh-CN 国际化配置
    * */
    const intl = useIntl();
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [loading, setLoading] = useState(false);
    // const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

    // const [showDetail, setShowDetail] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    // const [currentRow, setCurrentRow] = useState<TruckOrderVo>();
    // const [selectedRowsState, setSelectedRows] = useState<TruckOrderVo[]>([]);
    const [editRow, setEditRow] = useState<TruckOrderFeeDetailVO>();
    //  const [orderStatusEnum, setOrderStatusEnum] = useState<DictType[]>([]);
    const [tabChoice, setTabChoice] = useState<string>("ALL");
    const [selectType, setSelectType] = useState<string>("orderCode");
    const { initialState } = useModel("@@initialState");
    const { currentUser } = initialState || {};
    const [admin, setAdmin] = useState(currentUser?.isAdmin);





    const queryPageData = async (pageParams: TruckOrderFeeDetailVO) => {
        try {
            setLoading(true);
            const response = await pageCustomersListTruckOrderFees(pageParams);
            if (response.code != 0) {
                if (!response.msg) {
                    throw new Error(intl.formatMessage({ id: "request.error.create" }));
                } else {
                    message.error(response.msg);
                }
            }

            return response.data;
        } catch (error) {
            // console.error(error);
            // message.error(intl.formatMessage({ id: "request.error.retry" }));
            message.error(error.message || intl.formatMessage({ id: "request.error.default" }));
            return false;
        } finally {
            setLoading(false);
        }
    };






    const renderKeyValuePairs = (data: Record<string, string>) => (
        <div style={{ whiteSpace: 'pre-line' }}>
            {Object.entries(data).map(([key, value]) => `${key} ${value}`).join('\n')}
        </div>
    );




    const columns: ProColumns<TruckOrderFeeDetailVO>[] = [
        {
            title: intl.formatMessage({ id: 'pages.table.index', defaultMessage: '序号' }),
            valueType: 'index',
            // 可选的自定义序号样式
            render: (text, record, index) => (
                <span>{index + 1}</span>
            ),
            width: 80,
            align: 'center',
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.info"
                    defaultMessage="order info"
                />
            ),
            dataIndex: "info",
            key: "info",
            copyable: true,
            disable: true,
            width: 400,
            // ellipsis: true,
            render: (_, record) => renderKeyValuePairs({
                [intl.formatMessage({ id: 'pages.truckOrder.orderCode', defaultMessage: '订单号:' })]: record.orderCode,
                [intl.formatMessage({ id: 'pages.truckOrder.trackingNumber', defaultMessage: '物流单号:' })]: record.trackingNumber || '-',
                [intl.formatMessage({ id: 'pages.truckOrder.referenceNo', defaultMessage: '物流跟踪号:' })]: record.referenceNo || '-'
            }),
            search: {
                transform: (value) => ({ [value.searchType]: value.searchValue }),
                renderFormItem: () => (
                    <Input.Group compact style={{ display: 'flex', alignItems: 'center' }}>
                        <ProFormSelect
                            name="searchType"
                            initialValue="orderCode"  // 默认选择订单号
                            options={[
                                 { 
                                    label: intl.formatMessage({ id: 'pages.search.orderCode', defaultMessage: '订单号' }), 
                                    value: 'orderCode' 
                                },
                                { 
                                    label: intl.formatMessage({ id: 'pages.search.trackingNumber', defaultMessage: '物流单号' }), 
                                    value: 'trackingNumber' 
                                },
                                { 
                                    label: intl.formatMessage({ id: 'pages.search.referenceNo', defaultMessage: '跟踪号' }), 
                                    value: 'referenceNo' 
                                }
                            ]}
                            fieldProps={{
                                style: { width: 100 },
                                // bordered: false,        // 隐藏边框
                                dropdownMatchSelectWidth: false,
                                showSearch: true        // 允许搜索选项
                            }}
                            onChange={value => setSelectType(value)}
                        />
                        <ProFormText
                            name="searchValue"
                            placeholder={intl.formatMessage({ id: 'pages.search.placeholder', defaultMessage: '请输入' })}
                            width="md"
                            fieldProps={{
                                style: { marginLeft: 2 } // 消除间距
                            }}
                        />
                    </Input.Group>
                )
            }
        },

        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.customerCode"
                    defaultMessage="customerCode"
                />
            ),
            dataIndex: "customerCode",
            key: "customerCode",
            hideInForm: true,
            width: 150,
            ellipsis: true,
            search: {
                // 控制查询表单中的顺序
                transform: (value) => ({ customerCode: value }),
                order: 1,
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.productCode"
                    defaultMessage="productCode"
                />
            ),
            dataIndex: "productCode",
            key: "productCode",
            search: false,
            hideInForm: true,
            width: 150,
            ellipsis: true,
        },

        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.ofdAmount"
                    defaultMessage="ofdAmount"
                />
            ),
            dataIndex: "ofdAmount",
            key: "ofdAmount",
            search: false,
            hideInForm: true,
            // width: 100,
            ellipsis: true,
            render: (_, record) => {
                if (record.currencyCode) {
                    return (record.ofdAmount || '-') + " " + record.currencyCode;
                } else {
                    return (record.ofdAmount || '-') + " USD";
                }
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.ofdNote"
                    defaultMessage="ofdNote"
                />
            ),
            dataIndex: "ofdNote",
            key: "ofdNote",
            search: false,
            hideInForm: true,
            width: 100,
            ellipsis: true,
        },

        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.createTime"
                    defaultMessage="createTime"
                />
            ),
            dataIndex: "createTime",
            key: "createTime",
            search: false,
            ellipsis: true,
            render: (_, record) =>
                renderKeyValuePairs({
                    [intl.formatMessage({ id: 'pages.truckOrder.createTime', defaultMessage: '创建:' })]: formatToLocalTime(record.createTime),
                    [intl.formatMessage({ id: 'pages.truckOrder.updateTime', defaultMessage: '更新:' })]: formatToLocalTime(record.updateTime),
                }),
            hideInForm: true,
            width: 230,
        },
        ...(admin
            ? [
                {
                    title: <FormattedMessage id="pages.operating" defaultMessage="operating" />,
                    dataIndex: "option",
                    valueType: "option",
                    fixed: "right",
                    width: 120,
                    disable: true,
                    render: (_, record) => [
                        // 添加费用按钮（当 isExtend 为 0 时显示）
                        record.isExtend === 0 && (
                            <a
                                key="add"
                                onClick={async () => {
                                    setEditRow(record);
                                    setCreateModalOpen(true);
                                }}
                            >
                                <FormattedMessage id="pages.truckOrder.feeNew" defaultMessage="add new" />
                            </a>
                        ),

                        // 删除按钮（当 isExtend 大于 0 时显示）
                        record.isExtend > 0 && (
                            <a
                                key="delete"
                                onClick={async () => {
                                    await deleteTruckOrderExtendFee(record.ofdId);
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                }}
                            >
                                <FormattedMessage id="pages.delete" defaultMessage="delete" />
                            </a>
                        )
                    ].filter(Boolean), // 过滤掉条件不满足时的 false 值
                },
            ]
            : []),
    ];

    const [queryParams, setQueryParams] = useState<TruckOrderFeeDetailVO>();

    const pageQueryCustomer = async (params, sorter, filter) => {
        // 表单搜索项会从 params 传入，传递给后端接口。
        console.log(params, sorter, filter);
        const { current, pageSize, customerCode, searchType, searchValue } = params

        const queryParams: TruckOrderFeeDetailVO = {
            current: current,
            pageSize: pageSize
        };

        if (customerCode !== undefined) queryParams.customerCode = customerCode;

        if (searchType === "orderCode") queryParams.orderCode = searchValue;
        if (searchType === "trackingNumber") queryParams.trackingNumber = searchValue;
        if (searchType === "referenceNo") queryParams.referenceNo = searchValue;

        //  console.log(searchParams)
        //  form.submit();


        console.log(queryParams);
        setQueryParams(queryParams);
        return await queryPageData(queryParams);
    }

    const [tableParams, setTableParams] = useState<TableParams>({
        pagination: {
            current: 1,
            pageSize: 20,
        },
    });
    const handleExport = async () => {
        try {
            const params = {
                ...tableParams,
                pageSize: tableParams.pagination?.total,
            };
            const link = document.createElement('a');
            link.href = `/admin-api/system/truck-order/fee_info/export?${qs.stringify(queryParams)}`;
            link.download = 'export.xlsx'; // 指定文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            message.error(intl.formatMessage({ id: 'pages.export.error', defaultMessage: '导出失败' }));
            console.error(error);
        }
    };

    return (
        <PageContainer title={false}>
            <Card
                bordered={false}
                style={{ margin: -16 }} // 消除Card与Tab之间的间距
            >
                <ProTable<TruckOrderFeeDetailVO, API.PageParams>
                    headerTitle={intl.formatMessage({
                        id: "pages.truckOrder.list",
                        defaultMessage: "Order List",
                    })}
                    // actionRef={tabActionRefs.current[item.key]}
                    actionRef={actionRef}
                    loading={loading}
                    // dataSource={dataSource}
                    rowKey="key"
                    // params={tabChoice === item.key ? searchTableParams : {}}
                    // search={false}
                    // pagination={{
                    //     ...tableParams.pagination,
                    //     showSizeChanger: true,
                    //     pageSizeOptions: ["10", "20", "50", "100"],
                    // }}
                    request={pageQueryCustomer}
                    columns={columns}
                    scroll={{
                        x: "max-content", // 自动根据内容宽度计算
                        y: 900, // 固定高度触发垂直滚动
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="primary"
                            onClick={() => {
                                handleExport();
                            }}
                        >
                            <FormattedMessage id="pages.truckOrder.export" defaultMessage="Export" />
                        </Button>,
                    ]}
                    sticky // 表头吸顶
                />
            </Card>
            <EditForm
                visible={createModalOpen}
                values={editRow}
                onCancel={() => {
                    setCreateModalOpen(false);
                }}
                onSuccess={function (): void {
                    setCreateModalOpen(false);
                    //   setCurrentRow(undefined);
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }}
            />
        </PageContainer>
    );
};

export default TableList;
